package P014_SerializationPrivateField;

import P011_ExplicitDeclarationUID.SerializationUtils;
import org.junit.Test;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * Desc:&emsp;&ensp; 使用序列化类的私有方法巧妙解决部分属性持久化问题
 *
 * @author 李渊&emsp;liyuan7@yusys.com.cn
 * @version 1.0
 * @since V4.3&emsp;2022/2/24
 */
public class SerializationPrivateField {

    private static class Salary implements Serializable {
        private static final long serialVersionUID = 44663L;
        //基本工资
        private int basePay;
        //绩效工资
        private int bonus;
        public Salary(int basePay,int bonus){
            this.basePay = basePay;
            this.bonus =bonus;
        }

        public int getBasePay() {
            return basePay;
        }

        public Salary setBasePay(int basePay) {
            this.basePay = basePay;
            return this;
        }

        public int getBonus() {
            return bonus;
        }

        public Salary setBonus(int bonus) {
            this.bonus = bonus;
            return this;
        }
    }
    private static class Person implements Serializable {
        private static final long serialVersionUID = 60407L;
        private String name;
        //薪水
        private Salary salary;

        public Person(String name,Salary salary){
            this.name = name;
            this.salary = salary;
        }

        //序列化委托方法
        private void writeObject (ObjectOutputStream out) throws IOException {
            out.defaultWriteObject();
            out.writeInt(salary.getBasePay());
        }
        //反序列化时委托方法
        private void readObject(ObjectInputStream in) throws IOException,ClassNotFoundException {
            in.defaultReadObject();
            salary = new Salary(in.readInt(), 0);
        }

        public String getName() {
            return name;
        }

        public Person setName(String name) {
            this.name = name;
            return this;
        }

        public Salary getSalary() {
            return salary;
        }

        public Person setSalary(Salary salary) {
            this.salary = salary;
            return this;
        }
    }

    @Test
    public void TestHR() {
        //基本工资1000元，绩效工资2500元
        Salary salary = new Salary(1000,2500);
        //记录人员信息
        Person person = new Person ("张三",salary);
        //HR系统持久化，并传递到计税系统
        SerializationUtils.writeObject(person);

    }

    @Test
    public void TestTax() {
        //技术系统反序列化，并打印信息
        Person p = (Person)SerializationUtils.readObject();
        StringBuffer sb = new StringBuffer();
        sb.append("姓名：" + p. getName ());
        sb.append("\t 基本工资："+ p.getSalary().getBasePay());
        sb.append("\t 绩效工资："+ p.getSalary().getBonus());
        System.out.println (sb);
    }
}


